package com.lxhdj.management.security;

import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authorization.AuthorizationDecision;
import org.springframework.security.authorization.AuthorizationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.access.intercept.RequestAuthorizationContext;

import java.util.function.Supplier;

/**
 *  自定义权限管理器
 */
public class CustomAuthorizationManager implements AuthorizationManager<RequestAuthorizationContext> {

    @Override
    public AuthorizationDecision check(Supplier<Authentication> authentication, RequestAuthorizationContext context) {
        String requestURI = context.getRequest().getRequestURI(); // 请求路径
        // 1. 可以添加动态添放行路径，然后判断是否放行，若是，则返回 true
        if (requestURI.equals("/login")) { // 登录放行
            return new AuthorizationDecision(true);
        }
        Authentication auth = authentication.get();

        // 2. 未登录的匿名用户
        if (auth instanceof AnonymousAuthenticationToken) {
            return new AuthorizationDecision(false);
        }

        // 原来逻辑
        // 1. 启动加载配置中的所有配置，设置为AuthorizationManager 到过滤器中
        // 2. 每个规则对应一个RequestMatcherEntry
        // 3. 规则判断，返回是否授权
        return new AuthorizationDecision(true);
    }




}
